<?php

namespace App\Http\Controllers;

use App\Models\Transaction;
use App\Models\RoomUser;
use App\Models\Room;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TransactionController extends Controller
{
    /**
     * 添加交易记录
     */
    public function add(Request $request)
    {
        $user = $request->user;
        
        $this->validate($request, [
            'room_id' => 'required|integer',
            'to_user_id' => 'required|integer',
            'amount' => 'required|numeric|min:0.01',
            'type' => 'required|integer',
            'description' => 'max:200'
        ]);
        
        $roomId = $request->input('room_id');
        $toUserId = $request->input('to_user_id');
        $amount = $request->input('amount');
        $type = $request->input('type');
        $description = $request->input('description', '');
        
        // 检查房间是否存在
        $room = Room::find($roomId);
        if (!$room) {
            return response()->json([
                'code' => 404,
                'message' => '房间不存在'
            ]);
        }
        
        // 检查房间是否处于活跃状态
        if ($room->status != Room::STATUS_ACTIVE) {
            return response()->json([
                'code' => 400,
                'message' => '房间已关闭，无法进行交易'
            ]);
        }
        
        // 检查用户是否在房间内
        $fromRoomUser = RoomUser::where('room_id', $roomId)->where('user_id', $user->id)->first();
        $toRoomUser = RoomUser::where('room_id', $roomId)->where('user_id', $toUserId)->first();
        
        if (!$fromRoomUser || !$toRoomUser) {
            return response()->json([
                'code' => 403,
                'message' => '用户不在该房间内'
            ]);
        }
        
        // 开始事务
        DB::beginTransaction();
        
        try {
            // 创建交易记录
            $transaction = new Transaction();
            $transaction->room_id = $roomId;
            $transaction->from_user_id = $user->id;
            $transaction->to_user_id = $toUserId;
            $transaction->amount = $amount;
            $transaction->type = $type;
            $transaction->description = $description;
            $transaction->create_time = time();
            $transaction->save();
            
            // 更新房间用户积分
            if ($type == Transaction::TYPE_WIN) {
                $fromRoomUser->updateScoreChange(-$amount);
                $toRoomUser->updateScoreChange($amount);
            } elseif ($type == Transaction::TYPE_BET) {
                $fromRoomUser->updateScoreChange(-$amount);
            } elseif ($type == Transaction::TYPE_TRANSFER) {
                $fromRoomUser->updateScoreChange(-$amount);
                $toRoomUser->updateScoreChange($amount);
            }
            
            DB::commit();
            
            return response()->json([
                'code' => 200,
                'data' => [
                    'transaction_id' => $transaction->id,
                    'create_time' => $transaction->create_time
                ],
                'message' => '交易记录添加成功'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'code' => 500,
                'message' => '交易失败：' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 获取房间的交易记录
     */
    public function getRoomTransactions(Request $request, $roomId)
    {
        $user = $request->user;
        
        // 检查用户是否在房间内
        $roomUser = RoomUser::where('room_id', $roomId)->where('user_id', $user->id)->first();
        if (!$roomUser) {
            return response()->json([
                'code' => 403,
                'message' => '无权限查看此房间的交易记录'
            ]);
        }
        
        // 获取分页参数
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 20);
        
        // 查询交易记录
        $transactions = Transaction::where('room_id', $roomId)
            ->orderBy('create_time', 'desc')
            ->skip(($page - 1) * $pageSize)
            ->take($pageSize)
            ->get();
        
        $total = Transaction::where('room_id', $roomId)->count();
        
        // 格式化数据
        $formattedTransactions = [];
        foreach ($transactions as $transaction) {
            $formattedTransactions[] = [
                'id' => $transaction->id,
                'from_user' => [
                    'id' => $transaction->fromUser->id,
                    'nickname' => $transaction->fromUser->nickname,
                    'avatar' => $transaction->fromUser->avatar
                ],
                'to_user' => [
                    'id' => $transaction->toUser->id,
                    'nickname' => $transaction->toUser->nickname,
                    'avatar' => $transaction->toUser->avatar
                ],
                'amount' => $transaction->amount,
                'type' => $transaction->type,
                'type_name' => $transaction->getTypeName(),
                'description' => $transaction->description,
                'create_time' => $transaction->create_time
            ];
        }
        
        return response()->json([
            'code' => 200,
            'data' => [
                'transactions' => $formattedTransactions,
                'total' => $total,
                'page' => $page,
                'page_size' => $pageSize
            ]
        ]);
    }
    
    /**
     * 获取用户的统计数据
     */
    public function getUserStatistics(Request $request)
    {
        $user = $request->user;
        
        // 获取时间范围参数
        $startDate = $request->input('start_date', 0);
        $endDate = $request->input('end_date', time());
        
        // 查询用户的收支统计
        $income = Transaction::where('to_user_id', $user->id)
            ->whereBetween('create_time', [$startDate, $endDate])
            ->sum('amount');
        
        $expense = Transaction::where('from_user_id', $user->id)
            ->whereBetween('create_time', [$startDate, $endDate])
            ->sum('amount');
        
        // 查询最近的交易记录
        $recentTransactions = Transaction::where(function ($query) use ($user) {
                $query->where('from_user_id', $user->id)
                      ->orWhere('to_user_id', $user->id);
            })
            ->whereBetween('create_time', [$startDate, $endDate])
            ->orderBy('create_time', 'desc')
            ->take(10)
            ->get();
        
        // 格式化最近交易记录
        $formattedRecent = [];
        foreach ($recentTransactions as $transaction) {
            $formattedRecent[] = [
                'id' => $transaction->id,
                'room_name' => $transaction->room->name,
                'counterparty' => $transaction->from_user_id == $user->id ? 
                    $transaction->toUser->nickname : $transaction->fromUser->nickname,
                'amount' => $transaction->amount,
                'is_income' => $transaction->to_user_id == $user->id,
                'type' => $transaction->type,
                'type_name' => $transaction->getTypeName(),
                'create_time' => $transaction->create_time
            ];
        }
        
        return response()->json([
            'code' => 200,
            'data' => [
                'total_score' => $user->total_score,
                'win_count' => $user->win_count,
                'lose_count' => $user->lose_count,
                'win_rate' => $user->getWinRate(),
                'income' => $income,
                'expense' => $expense,
                'net_income' => $income - $expense,
                'recent_transactions' => $formattedRecent
            ]
        ]);
    }
}